<template>
  <!-- 页面整体布局外层容器 -->
  <div class="flex flex-wrap gap-4">
    <el-card style="font-size: 15px;font-weight: bold;margin-bottom: 10px" shadow="always"><span style="color: #535bf2">|</span>商品类型页</el-card>
  </div>
  <div class="userList" style="padding-top: 30px">
    <!-- 商品类型搜索表单 -->
    <el-form style="margin-left: 15px " :inline="true" :model="productTypeSearchQuery">
<!--      <el-form-item label="请选择商品类型：">-->
<!--        <el-select style="width: 150px"-->
<!--                   v-model="productTypeSearchQuery.productTypeId"-->
<!--                   placeholder="请选择商品类型"-->
<!--                   @click="loadProductTypeOptions"-->
<!--                   clearable>-->
<!--          <el-option-->
<!--              v-for="item in productTypeOptions"-->
<!--              :key="item.id"-->
<!--              :label="item.productTypeName"-->
<!--              :value="item.id"/>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
    </el-form>
    <!-- 添加类型按钮 -->
    <el-button style="margin-left: 15px;" type="primary" @click="addView">添加类型</el-button>
    <!-- 批量删除按钮，点击触发 batchDel 方法来执行批量删除操作，根据选中的商品类型 ID 进行删除 -->
    <el-button type="danger" @click="batchDel">批量删除</el-button>
    <!-- 商品类型列表展示表格 -->
    <el-table
        :data="productTypeList"
        style="width: auto"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" show-overflow-tooltip/>
      <el-table-column type="index" label="序号" width="200" show-overflow-tooltip/>
      <el-table-column prop="id" label="ID" width="200" show-overflow-tooltip/>
      <el-table-column prop="productTypeName" label="类型名" width="200" show-overflow-tooltip/>
      <el-table-column prop="productTypeDesc" label="描述" width="200" show-overflow-tooltip/>
      <el-table-column prop="productTypeIcon" label="图标" width="200" show-overflow-tooltip/>
      <el-table-column style="" label="操作" width="230">
        <template #default="scope">
          <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
          <el-button type="success" @click="editView(scope.row.id)">编辑</el-button>
          <el-button type="danger" @click="delUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination style="justify-content: center;margin-top: 10px"
                   background
                   layout="prev, pager,next"
                   :page-size="pageSize"
                   :total="total"
                   @current-change="toPage"
                   @prev-click="toPage"
                   @next-click="toPage"
    />
    <!-- 添加商品类型弹窗 -->
    <el-dialog v-model="addDialogVisible" width="1000px" :title="addDialogTitle"
               draggable="true" center>
      <el-form ref="addRefForm" :model="addProductTypeQuery" label-width="auto" :rules="addRules" style="max-width: 800px">
        <el-form-item label="类型名：" prop="productTypeName" :rules="[{ required: true, message: '请输入类型名', trigger: 'blur' }]">
          <el-input v-if="addProductTypeQuery.id == null" v-model="addProductTypeQuery.productTypeName" placeholder="请输入类型名"/>
          <span class="detail" v-else>{{ addProductTypeQuery.productTypeName }}</span>
        </el-form-item>
        <el-form-item label="描述：" prop="productTypeDesc" :rules="[{ required: true, message: '请输入描述', trigger: 'blur' }]">
          <el-input v-if="addProductTypeQuery.id == null" v-model="addProductTypeQuery.productTypeDesc" placeholder="请输入描述"/>
          <span class="detail" v-else>{{ addProductTypeQuery.productTypeDesc }}</span>
        </el-form-item>
        <el-form-item label="图标：" prop="productTypeIcon" :rules="[{ required: true, message: '请输入图标链接', trigger: 'blur' }]">
          <el-input v-if="addProductTypeQuery.id == null" v-model="addProductTypeQuery.productTypeIcon" placeholder="请输入图标链接或选择图标"/>
          <span class="detail" v-else>{{ addProductTypeQuery.productTypeIcon }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button v-if="addProductTypeQuery.id==null" type="primary" @click="addProductTypeSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 编辑商品类型弹窗 -->
    <el-dialog v-model="editDialogVisible" width="1000px" draggable="true" center>
      <el-form ref="editRefForm" :model="editProductTypeQuery" label-width="auto" :rules="editRules" style="max-width: 800px">
        <el-form-item label="ID：" prop="id">
          <span class="detail">{{ editProductTypeQuery.id }}</span>
        </el-form-item>
        <el-form-item label="类型名：" prop="productTypeName" :rules="[{ required: true, message: '请输入类型名', trigger: 'blur' }]">
          <el-input v-model="editProductTypeQuery.productTypeName"/>
        </el-form-item>
        <el-form-item label="描述：" prop="productTypeDesc" :rules="[{ required: true, message: '请输入描述', trigger: 'blur' }]">
          <el-input v-model="editProductTypeQuery.productTypeDesc"/>
        </el-form-item>
        <el-form-item label="图标：" prop="productTypeIcon" :rules="[{ required: true, message: '请输入图标链接', trigger: 'blur' }]">
          <el-input v-model="editProductTypeQuery.productTypeIcon"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editProductTypeSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import { messageConfirm, messageTip } from "../util/util.js";
import qs from "qs";

export default {
  name: "ProductTypeView",
  inject: ['reload'],
  data() {
    return {
      productTypeList: [], // 存储商品类型列表数据
      addDialogVisible: false, // 控制添加商品类型弹窗的显示隐藏
      addProductTypeQuery: {}, // 用于添加商品类型时的数据绑定对象
      pageSize: 0, // 每页展示的商品类型数据条数
      total: 0, // 商品类型数据总条数
      selectedProductTypeIds: [], // 用于记录批量删除时选中的商品类型 ID 数组
      editDialogVisible: false, // 控制编辑商品类型弹窗的显示隐藏
      editProductTypeQuery: {}, // 编辑商品类型时的临时数据对象
      addRules: {
        productTypeName: [
          { required: true, message: '请输入类型名', trigger: 'blur' }
        ],
        productTypeDesc: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        productTypeIcon: [
          { required: true, message: '请输入图标链接', trigger: 'blur' }
        ]
      },
      editRules: {
        productTypeName: [
          { required: true, message: '请输入类型名', trigger: 'blur' }
        ],
        productTypeDesc: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        productTypeIcon: [
          { required: true, message: '请输入图标链接', trigger: 'blur' }
        ]
      },
      productTypeSearchQuery: {}, // 存储商品类型搜索表单中的数据（包含选择的商品类型 ID 等）
      productTypeOptions: [] // 商品类型下拉框的选项数据（根据实际查询结果填充）
    }
  },
  mounted() {
    this.loadProductTypeList(1); // 页面加载时，加载第一页商品类型列表数据
  },
  methods: {
    // 切换分页时加载对应页的商品类型列表数据
    toPage(current) {
      this.loadProductTypeList(current);
    },
    // 处理商品类型列表中选中行变化时的事件，记录选中的商品类型 ID
    handleSelectionChange(productTypeItemArray) {
      this.selectedProductTypeIds = [];
      productTypeItemArray.forEach((productType) => {
        this.selectedProductTypeIds.push(productType.id);
      })
    },
    // 加载商品类型列表数据的方法，根据传入的页码参数获取对应页数据
    loadProductTypeList(current) {
      doGet("/admin/ProductType", {
        current: current
      }).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.productTypeList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      })
    },
    // 删除单个商品类型的方法，弹出确认框后，根据商品类型 ID 发送删除请求到后端
    delUser(id) {
      messageConfirm("是否删除该商品类型？").then(() => {
        doDelete("/admin/ProductType/" + id).then((resp) => {
          if (resp.data.code === 200) {
            messageTip("删除成功!", "success");
            this.reload();
          }
        })
      })
    },
    // 批量删除商品类型的方法，将选中的商品类型 ID 数组拼接成字符串发送到后端进行批量删除
    batchDel() {
      if (this.selectedProductTypeIds.length === 0) {
        messageTip('请先选择要批量删除的商品类型', 'warning');
        return;
      }
      let ids = this.selectedProductTypeIds.join(",");
      doGet("/admin/ProductType?method=deleteByIds", {
        ids: ids
      }).then((resp) => {
        if (resp.data.code === 200) {
          messageTip("批量删除成功", "success");
          this.reload();
        } else {
          messageTip("批量删除失败，请查看详情", "error");
        }
      });
    },
    // 点击添加商品类型按钮，清空 addProductTypeQuery 并打开添加商品类型弹窗
    addView() {
      this.addProductTypeQuery = {};
      this.addDialogVisible = true;
      this.addDialogTitle = "添加商品类型";
    },
    // 执行添加商品类型的方法，先进行表单验证，通过后将表单数据序列化发送 POST 请求到后端添加商品类型接口
    addProductTypeSubmit() {
      this.$refs.addRefForm.validate((valid) => {
        if (valid) {
          doPost("/admin/ProductType/save", this.addProductTypeQuery).then((resp) => {
            if (resp.data.code === 200) {
              this.addDialogVisible = false;
              messageTip("添加成功", "success");
              this.reload();
            } else {
              messageTip("添加失败", "error");
            }
          });
        } else {
          console.log('表单验证未通过，请检查输入信息');
          return false;
        }
      });
    },
    // 根据商品类型 ID 查询商品类型详情
    view(id) {
      doGet("/admin/ProductType/" + id).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.addProductTypeQuery = resp.data.data;
          this.addDialogVisible = true;
          this.addDialogTitle = "商品类型详情";
        }
      })
    },
    // 根据商品类型 ID 查询商品类型数据用于编辑
    editView(id) {
      doGet("/admin/ProductType/" + id).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.editProductTypeQuery = resp.data.data;
          this.editDialogVisible = true;
        }
      })
    },
    // 执行编辑商品类型提交的方法，将编辑后的表单数据序列化发送 POST 请求到后端更新商品类型接口
    editProductTypeSubmit() {
      doPut("/admin/ProductType", this.editProductTypeQuery).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.editDialogVisible = false;
          messageTip("修改成功！", "success");
          this.reload();
        }
      })
    },
    // 加载商品类型下拉框的选项数据（根据实际需求查询所有商品类型或部分商品类型数据用于下拉框展示）
    loadProductTypeOptions() {
      doGet("/admin/ProductType?method=findAll", {})
          .then((resp) => {
            console.log(resp.data.data.list);
            if (resp.data.code === 200) {
              this.productTypeOptions = resp.data.data.list;
            }
          });
    },
    // 商品类型搜索功能，根据选择的商品类型 ID 等条件查询商品类型列表数据
    onSearch() {
      console.log(this.productTypeSearchQuery.productTypeId);
      doGet("/admin/ProductType?method=searchByCondition", {
        productTypeId: this.productTypeSearchQuery.productTypeId
      }).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.productTypeList = resp.data.data;
          this.reload();
        }
      })
    },
    // 重置商品类型搜索表单数据，清空选择的商品类型 ID 等条件
    onReset() {
      this.productTypeSearchQuery = {};
    }
  }
}
</script>

<style scoped>
.userList {
  width: auto;
  height: auto;
  background-color: #ffffff;
}

.detail {
  background-color: #f5f7fa;
  width: 100%;
  padding-left: 15px;
}
</style>